package com.scrcu.cloud.wechat.home.endpoint.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.*;
import java.net.URL;
import java.security.Key;

public class Encrypt
{
    /** 指定加密算法为 */
    private static String ALGORITHM = "RSA";


    private static Logger logger = LoggerFactory.getLogger(Encrypt.class);
    /**
     * 加密方法 source： 源数据
     */
    public static String encrypt(String source)
    {
        if(source==null||"".equals(source))
        {
            return "";
        }

        URL url = Thread.currentThread().getContextClassLoader().getResource("config/scrcu/images/en.gif");

        /** 将文件中的公钥对象读出 */
        String enString = null;
        DataInputStream ois_2 = null;
        ObjectInputStream ois = null;
        try
        {
            ois_2 = new DataInputStream(new FileInputStream(url.getPath()));
            //DataInputStream ois_2 = new DataInputStream(new FileInputStream("D:/workspaceSCRCU_SMS/pscrcu/src/config/scrcu/images/en.gif"));
            byte[] total = new byte[1421];
            ois_2.read(total);
            byte[] source_2 = new byte[351];
            System.arraycopy(total, 1070, source_2, 0, 351);
            ois = new ObjectInputStream(new ByteArrayInputStream(source_2));
            Key key = (Key) ois.readObject();
            /** 得到Cipher对象来实现对源数据的RSA加密 */
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] b = source.getBytes();
            /** 执行加密操作 */
            byte[] b1 = cipher.doFinal(b);
            BASE64Encoder encoder = new BASE64Encoder();
            enString =  encoder.encode(b1);
        }
        catch(Exception e)
        {
            logger.error("加密异常：" + e);
        }
        finally {
            if (null != ois_2) {
                safeClose(ois_2);
            }
            if (null != ois) {
                safeClose(ois);
            }
        }
        return enString;
    }

    /**
     * 解密算法 cryptograph:密文
     */
    public static String decrypt(String cryptograph)
    {
        if(cryptograph==null||"".equals(cryptograph))
        {
            return "";
        }
        /** 将文件中的私钥对象读出 */
        String deString = null;
//        URL url = Thread.currentThread().getContextClassLoader().getResource("config/scrcu/images/de.gif");
//        URL url = Thread.currentThread().getClass().getClassLoader().getResource("/config/scrcu/images/de.gif");
        InputStream input=Thread.currentThread().getContextClassLoader().getResourceAsStream("config/scrcu/images/de.gif");
        DataInputStream ois_1 = null;
        ObjectInputStream ois = null;
        try
        {
//            ois_1 = new DataInputStream(new FileInputStream(url.getPath()));
            ois_1 = new DataInputStream(input);
            //DataInputStream ois_1 = new DataInputStream(new FileInputStream("D:/workspaceSCRCU_SMS/pscrcu/src/config/scrcu/images/de.gif"));
            byte[] total = new byte[1672];
            ois_1.read(total);
            byte[] source = new byte[602];
            System.arraycopy(total, 1070, source, 0, 602);
            ois = new ObjectInputStream(new ByteArrayInputStream(source));
            Key key = (Key) ois.readObject();
            /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b1 = decoder.decodeBuffer(cryptograph);
            /** 执行解密操作 */
            byte[] b = cipher.doFinal(b1);
            deString = new String(b);
        }
        catch (Exception e)
        {
            logger.error("解密异常：" + e);
        }finally {
            if (null != ois_1) {
                safeClose(ois_1);
            }
            if (null != ois) {
                safeClose(ois);
            }
        }
        return deString;
    }

    public static void safeClose(DataInputStream intPutFile) {
        if (intPutFile != null) {
            try {
                intPutFile.close();
            } catch (IOException e) {
                logger.error("关闭文件流异常:"+e.getMessage());
            }
        }
    }
    public static void safeClose(ObjectInputStream inPutFile) {
        if (inPutFile != null) {
            try {
                inPutFile.close();
            } catch (IOException e) {
                logger.error("关闭文件流异常:"+e.getMessage());
            }
        }
    }

    public static void main(String[] args)
    {
        System.out.println(new Encrypt().encrypt("SmsDB123"));
        // System.out.println();
        // System.out.println(new Encrypt().decrypt("XKa8SOUq7aCuWqRQWwGgz8++vcayOPqBAAbZGk1lEABqrlKtkYG6BOH835tnpKxTEh7taEFHppw+ylC0IH2E1w=="));
        // System.out.println();
        //  System.out.println(new Encrypt().decrypt("kNtNuEdWldDwYRIVBfiFF9cdwNkcRWmI22NR78z8VEYZn1amaLTazZG6uAEtrNF8xW+WvkM2GSZeEcMQM6C4NA=="));
        //  System.out.println();
        //System.out.println(new Encrypt().decrypt("ShCHU+wAhzSJuZW5siUh7ZLAWMxw651F1Qx2xC5SGL0TdToaOCoPBe7/6wq+cBgB8JLZOF05dRpiI8ZFzJ9SXA=="));

        System.out.println(new Encrypt().decrypt("FErm4fAbrNKXO3z1jYx3KE38YOuVcWPRExThBQFhw+GSwd/QHulKXQxF+nm8WieQlRrKKQNMJ7pqTG0jVToGiQ=="));
    }
}
